require 'digest/sha1'

class User < ActiveRecord::Base
  validates_presence_of :login,
                        :password,
                        :password_confirmation,
                        :first_name,
                        :last_name
                        
  validates_uniqueness_of :login
  
  attr_accessor :password_confirmation
  validates_confirmation_of :password
  
  def password
    @password
  end
  
  def password=(pwd)
    @password = pwd
    create_new_salt
    self.hashed_password = User.encrypt_password(self.password, self.salt)
  end
  
  def self.authenticate(login, password)
    user = self.find_by_login(login)
    if user
      expected_password = encrypt_password(password, user.salt)
      if user.hashed_password != expected_password
        user = nil
      end
    end
    user
  end
  
  def safe_delete
    transation do
      destroy
      if User.count.zero?
        raise "Can't delete last user"
      end
    end
  end
  
  private
  
  def self.encrypt_password(password, salt)
    string_to_hash = password + "yoda" + salt
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
  def create_new_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
  
end
